<template>
  <div @keyup.enter="getData()">
    <el-form @submit.native.prevent :inline="true">
      <el-form-item>
        <el-input placeholder="部门名称" v-model="params.deptName"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="getData()">查询</el-button>
        <el-button v-if="power" @click="dialogVisible = true">新建部门</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" border v-loading="loading">
      <el-table-column label="部门名称" prop="deptName" align="center"></el-table-column>
      <el-table-column label="描述" prop="deptDescription" align="center"></el-table-column>
      <el-table-column label="操作" v-if="power" align="center">
        <template slot-scope="scope" align="center">
          <el-button size="mini" @click="onModify(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            v-if="+scope.row.deptParentId !== -1"
            @click="confirmDelete(scope.row)"
            type="danger"
            plain
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="query-pagination">
      <div class="text-muted p-2">共 {{ tableTotal }} 个部门</div>
    </div>

    <el-dialog
      :title="`${selectDept.deptName ? '修改' : '新建'}部门`"
      top="30px"
      width="40%"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
    >
      <el-form label-width="100px" :model="selectDept" :rules="rules" ref="form">
        <el-form-item label="部门名称" prop="deptName">
          <el-input placeholder="部门名称" v-model="selectDept.deptName"></el-input>
        </el-form-item>
        <el-form-item label="部门描述">
          <el-input
            placeholder="部门描述"
            type="textarea"
            :rows="5"
            v-model="selectDept.deptDescription"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" :loading="dialogLoading">保 存</el-button>
          <el-button @click="handleVisible">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { getDept, createDept, updateDept, deleteDept } from '@/common/api/auth'
import { cookieGet } from '@vimi/utils-tool'

export default {
  components: {},

  props: {},

  data() {
    return {
      params: {
        deptLevel: '',
        clientId: '',
        deptName: '',
      },
      tableData: [],
      tableTotal: 0,
      loading: false,
      // 修改、添加
      dialogVisible: false,
      dialogLoading: false,
      selectDept: {},
      clientId: '',
      editType: false,
      rules: {
        deptName: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
      },
    }
  },

  computed: {
    job() {
      return this.$store.getters.user.job
    },
    power() {
      return this.job === 'org_corp'
    },
  },

  watch: {},

  created() {
    this.getData()
  },

  mounted() {
    this.selectDept = this.resetDept()
  },

  methods: {
    getData() {
      this.loading = true
      getDept(this.params)
        .then(res => {
          this.tableData = res.data || []
          this.tableTotal = this.tableData.length
        })
        .finally(() => {
          this.loading = false
        })
    },

    confirmDelete(row) {
      this.$confirm(`确定删除部门：${row.deptName}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.deleteDept(row.deptId)
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },

    deleteDept(deptId) {
      deleteDept({
        clientId: this.clientId,
        deptId,
      })
        .then(res => {
          if (res.data > 0) {
            this.getData()
            this.$store.dispatch('getDeptData')
            this.$message.success('删除成功')
          } else {
            this.$message.error('删除失败，请重试！')
          }
        })
        .catch(() => {
          this.$message.error('删除失败，请重试！')
        })
    },

    onModify(row) {
      this.editType = true
      this.selectDept = { ...row }
      this.dialogVisible = true
    },

    handleClose(done) {
      this.resetForm()
      done()
    },

    handleVisible() {
      this.resetForm()
      this.dialogVisible = false
    },

    resetForm() {
      this.editType = false
      this.selectDept = this.resetDept()
      this.$refs.form.resetFields()
    },

    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.editType) {
            this.putDept()
          } else {
            this.postDept()
          }
        } else {
          this.$message.error('输入错误，请重新输入！')
        }
      })
    },

    putDept() {
      this.dialogLoading = true
      updateDept(this.selectDept)
        .then(res => {
          if (res.data > 0) {
            this.$message.success('修改部门成功')
            this.$store.dispatch('getDeptData')
            this.handleVisible()
            this.getData()
          } else {
            this.$message.info('修改部门失败，请重试！')
          }
        })
        .catch(() => {
          this.$message.error('修改部门失败，请重试！')
        })
        .then(() => {
          this.dialogLoading = false
        })
    },

    postDept() {
      this.dialogLoading = true
      this.selectDept.clientId = this.getClientId()
      this.selectDept.deptId = this.getDeptId() + ''
      createDept(this.selectDept)
        .then(res => {
          if (res.data > 0) {
            this.$message.success('添加部门成功')
            this.$store.dispatch('getDeptData')
            this.handleVisible()
            this.getData()
          } else {
            this.$message.info('添加部门失败，请重试！')
          }
        })
        .catch(() => {
          this.$message.error('添加部门失败，请重试！')
        })
        .then(() => {
          this.dialogLoading = false
        })
    },

    getDeptId() {
      let index = this.tableTotal
      do {
        index++
      } while (this.tableData.findIndex(it => it.deptId === index + '') > -1 && index < 10000)
      return index
    },

    getClientId() {
      let cookie = cookieGet('vimiauth')
      if (cookie) {
        let ids = JSON.parse(cookie)
        return ids.clientId
      }
      return ''
    },

    resetDept() {
      return {
        deptName: '',
        deptDescription: '',
        deptParentId: '0',
        deptResources:
          'auth-server|ebb-platform|industrial-platform|info-server|data-directory|merchant-platform',
        deptScopes: 'user-me',
      }
    },
  },
}
</script>

<style scoped></style>
